import datetime
import json
from json.encoder import JSONEncoder
from django.core.paginator import Paginator
from django.db.models.fields import DateTimeCheckMixin, DateTimeField
from django.db.models import Q
from django.http.response import JsonResponse
from django.shortcuts import render
from django.utils import timezone
from laundry_system.models import Merchant, Role, Customer, MCloth, Cloth, Order
# Create your views here.

# def home(request):
#     """
#     首页
#     """
#     return render(request, 'index.html')


def register(request):
    """
    注册函数
    """
    try:
        username = request.POST.get("username")
        password = request.POST.get("password")
        realname = request.POST.get("realname")
        sex = request.POST.get("sex")
        address = request.POST.get("address")
        tel = request.POST.get("tel")
        if sex == '男':
            i = 1
        else:
            i = 0
        role = Role.objects.filter(username=username)
        if role:
            result = False
        else:
            result = True
            user = Role(username=username, password=password,role=1)
            user.save()
            Customer.objects.create(user=user, sex=i, realname=realname, address=address, tel=tel)
    except Exception as err:
        result = False
        message = str(err)
    else:
        message = "Register success!"
    return JsonResponse({"result": result, "message": message})


def login(request):
    """
    登录函数
    """
    try:
        username = request.POST.get("username")
        password = request.POST.get("password")
        role = request.POST.get("role")
        i = -1
        # print(username)
        if role == '商家':
            i = 0
        if role == '客户':
            i = 1
        if i != -1:
            isUSer = Role.objects.get(username=username, password=password, role=i)
        if isUSer:
            result = True
    except Exception as err:
        result = False
        message = str(err)
    else:
        message = "Login success!"
    return JsonResponse({"result": result, "message": message, "role":role})


def getprice_customer(request):
    """
    获得价格函数
    """
    try:
        result_data = []
        username = request.POST.get("merchant")
        clothprice = MCloth.objects.filter(merchant__user__username=username)
        for item in clothprice:
            result_data.append(
                {
                    "id":item.id,
                    "type": item.type,
                    "Washmethod": item.Washmethod,
                    "price": item.price
                }
            )
    except Exception as err:
        result = False
        message = str(err)
    else:
        result = True
        message = "success!"
    return JsonResponse({"result": result, "message": message, "result_data":result_data })


def getprice_merchant(request):
    """
    获得价格函数
    """
    try:
        username = request.POST.get("merchant")
        result_data = []
        num = 0
        page = request.POST.get("page")
        clothprice = MCloth.objects.filter(merchant__user__username=username)
        p = Paginator(clothprice, 10)
        num = len(clothprice)
        page_clothprice = p.get_page(page)
        for item in page_clothprice:
            result_data.append(
                {
                    "id":item.id,
                    "type": item.type,
                    "Washmethod": item.Washmethod,
                    "price": item.price
                }
            )
    except Exception as err:
        result = False
        message = str(err)
    else:
        result = True
        message = "success!"
    return JsonResponse({"result": result, "message": message, "result_data":result_data ,"num":num})


def getpricebyid(request):
    """
    获得价格函数
    """
    try:
        username = request.POST.get("merchant")
        id = request.POST.get("clothid")
        clothprice = MCloth.objects.filter(id=id, merchant__user__username=username).first()
        result_data = {
            "id":clothprice.id,
            "type": clothprice.type,
            "Washmethod": clothprice.Washmethod,
            "price": clothprice.price
        }
    except Exception as err:
        result = False
        message = str(err)
    else:
        result = True
        message = "success!"
    return JsonResponse({"result": result, "message": message, "result_data":result_data})


def saveprice(request):
    """
    修改价格
    """
    try:
        # username = request.POST.get("username")
        id = request.POST.get("id")
        type = request.POST.get("type")
        price = request.POST.get("price")
        MCloth.objects.filter(id=id).update(type=type, price=price)    
    except Exception as err:
        result = False
        message = str(err)
    else:
        result = True
        message = "success!"
    return JsonResponse({"result": result, "message": message})


def addprice(request):
    """
    添加价格
    """
    try:
        username = request.POST.get("merchant")
        type = request.POST.get("type")
        price = request.POST.get("price")
        Washmethod = request.POST.get("Washmethod")
        if Washmethod == "普通洗":
            i = 0
        if Washmethod == "超强洗":
            i = 1
        merchant_id = Merchant.objects.filter(user__username=username).first().id
        MCloth.objects.create(type=type, price=price, Washmethod=i, merchant_id=merchant_id) 
    except Exception as err:
        result = False
        message = str(err)
    else:
        result = True
        message = "success!"
    return JsonResponse({"result": result, "message": message})


def deleteprice(request):
    """
    删除价格
    """
    try:
        id = request.POST.get("id")
        MCloth.objects.filter(id=id).delete()
    except Exception as err:
        result = False
        message = str(err)
    else:
        result = True
        message = "success!"
    return JsonResponse({"result": result, "message": message})


def getmerlist(request):
    """
    获得商户列表
    """
    try:
       merlist = Merchant.objects.all()
       result_data = []
       for item in merlist:
           result_data.append(
               {    
                   "username":item.user.username,
                   "realname":item.realname,
                   "address":item.address
               }
           )

    except Exception as err:
        result = False
        message = str(err)
    else:
        result = True
        message = "success!"
    return JsonResponse({"result": result, "message": message, "result_data":result_data})


def getmerchant(request):
    """
    获得商户信息
    """
    try:
        result_data = []
        now = datetime.datetime.utcnow()
        past = now + datetime.timedelta(days=-15)
        merlist = Merchant.objects.all()
        for item in merlist:
           order_num = len(Order.objects.filter(merchant_id=item.id, update_time__range=(past, now)))
           result_data.append(
               {    
                   "username":item.user.username,
                   "realname":item.realname,
                   "tel":item.tel,
                   "address":item.address,
                   "ordernum":order_num,
                   "rates":round(item.rate_speed, 2),
                   "ratep":round(item.rate_price, 2),
                   "rateq":round(item.rate_quality, 2)
               }
            )
        result_data.sort(key=lambda x:x['ordernum'],reverse=True)
    except Exception as err:
        result = False
        message = str(err)
    else:
        result = True
        message = "success!"
    return JsonResponse({"result": result, "message": message, "result_data":result_data})


def placeorder(request):
    """
    下单函数
    """
    try:
        order_data = json.loads(request.POST.get("data"))
        mername = request.POST.get("mername")
        cusname = request.POST.get("username")
        total = request.POST.get("total")
        Merchant_user = Role.objects.filter(username=mername).first()
        Customer_user = Role.objects.filter(username=cusname).first()
        merchant = Merchant.objects.filter(user=Merchant_user).first()
        customer = Customer.objects.filter(user=Customer_user).first()
        order = Order.objects.create(merchant_id=merchant.id, customer_id=customer.id, status = "下单成功", total=total)

        for item in order_data:
            type = item['type']
            Washmethod = item['Washmethod']
            price = item['price']
            num = item['num']
            if Washmethod == '普通洗':
                i = 0
            if Washmethod == '超强洗':
                i = 1
            if num != 0:
                Cloth.objects.create(type=type, Washmethod=i, num=num, price=price, order_id=order.id)# 订单中衣服中的某类衣服及其数量
    except Exception as err:
        result = False
        message = str(err)
        print(err)
    else:
        result = True
        message = "success!"
    return JsonResponse({"result": result, "message": message,"result_data":order_data})


def getorderby_id(request):
    """
    查询订单函数
    """
    try:
        result_data = []
        order_status = {}
        order_id = request.POST.get("order_id")
        data = Cloth.objects.filter(order_id=order_id)
        order = Order.objects.filter(id=order_id).first()
        Rate = {
            "isRated":str(order.is_Rated),
            "rates":order.rate_speed,
            "ratep":order.rate_price,
            "rateq":order.rate_quality,
            "show":order.status

        }
        for item in data:
            result_data.append(
                {
                    "type": item.type,
                    "Washmethod": item.Washmethod,
                    "price": round(item.price, 1),
                    "num": item.num
                }
            )
        order_status = {
            "status":order.status,
            "updatatime":timezone.localtime(order.update_time).strftime("%Y-%m-%d %H:%M:%S")
        }
    except Exception as err:
        result = False
        message = str(err)
        print(err)
    else:
        result = True
        message = "success!"
    return JsonResponse({"result": result, "message": message, "result_data":result_data, "order_status":order_status, "Rate":Rate})


def getordering(request):
    """
    查询正在进行的订单函数
    """
    try:
        result_data = []
        status = "订单完成"
        username = request.POST.get("username")
        orders = Order.objects.filter(~Q(status=status), customer__user__username=username)# 查询所有没有结束的订单
        for order in orders:
            merchant_realname = Merchant.objects.filter(id = order.merchant_id).first().realname
            result_data.append(
                {
                    "id":order.id,
                    "merchant_realname":merchant_realname,
                    "total":round(order.total, 1),
                    "status":order.status,
                    "updatetime":timezone.localtime(order.update_time).strftime("%Y-%m-%d %H:%M:%S")
                }
            )
    except Exception as err:
        result = False
        message = str(err)
        print(err)
    else:
        result = True
        message = "success!"
    return JsonResponse({"result": result, "message": message, "result_data":result_data})


def getallordersby_cus(request):
    """
    客户查询所有订单
    """
    try:
        result_data = []
        status = "订单完成"
        customer_name = request.POST.get("username")
        page = request.POST.get("page")
        orders = Order.objects.filter(status=status, customer__user__username=customer_name)
        num = len(orders)
        p = Paginator(orders, 10)
        page_orders = p.get_page(page)
        for item in page_orders:
            merchant_username = Merchant.objects.filter(id=item.merchant_id).first().user.username
            merchant_realname = Merchant.objects.filter(id=item.merchant_id).first().realname
            result_data.append(
                {
                    "id":str(item.id),
                    "merchantusername":merchant_username,
                    "merchantrealname":merchant_realname,
                    "updatetime":timezone.localtime(item.update_time).strftime("%Y-%m-%d %H:%M:%S"),
                    "total":round(item.total, 1),
                    "status":item.status,
                    "isRated":str(item.is_Rated)
                }
            )
    except Exception as err:
        result = False
        message = str(err)
        print(err)
    else:
        result = True
        message = "success!"
    return JsonResponse({"result": result, "message": message, "result_data":result_data,"num":num})


def getselfinfo(request):
    """
    查询个人资料
    """
    try:
        result_data = {}
        Rate = {}
        username = request.POST.get("username")
        role = Role.objects.filter(username=username).first().role
        if role == 1:
            userinfo = Customer.objects.filter(user__username=username).first()
            result_data = {
            "username":userinfo.user.username,
            "realname":userinfo.realname,
            "sex":userinfo.sex,
            "address":userinfo.address,
            "tel":userinfo.tel
            }
        else :
            userinfo = Merchant.objects.filter(user__username=username).first()
            result_data = {
                "username":userinfo.user.username,
                "realname":userinfo.realname,
                "address":userinfo.address,
                "tel":userinfo.tel
            }
            Rate = {
            "rates":round(userinfo.rate_speed, 2),
            "ratep":round(userinfo.rate_price, 2),
            "rateq":round(userinfo.rate_quality, 2)
        }
            
    except Exception as err:
        result = False
        message = str(err)
        print(err)
    else:
        result = True
        message = "success!"
    return JsonResponse({"result": result, "message": message, "result_data":result_data, "rate":Rate})


def saveinfo(request):
    """
    修改个人资料
    """
    try:
        username = request.POST.get("username")
        realname = request.POST.get("realname")
        address = request.POST.get("address")
        tel = request.POST.get("tel")
        user_role = Role.objects.filter(username=username).first().role
        if user_role == 0:
            # 商户没有性别这个字段
            Merchant.objects.filter(user__username=username).update(realname=realname, address=address, tel=tel)
        if user_role == 1:
            sex = request.POST.get("sex")
            if sex == "女":
                i = 0
            if sex == "男":
                i = 1
            Customer.objects.filter(user__username=username).update(realname=realname, address=address, tel=tel, sex=i)
    except Exception as err:
        result = False
        message = str(err)
        print(err)
    else:
        result = True
        message = "success!"
    return JsonResponse({"result": result, "message": message})


def getunderway(request):
    """
    获得所有正在进行中的订单
    """
    try:
        merchant_name=request.POST.get("username")
        page = request.POST.get("page")
        result_data = []
        status = "订单完成"
        orders = Order.objects.filter(~Q(status=status), merchant__user__username=merchant_name)# 查询所有没有结束的订单
        num = len(orders)
        p = Paginator(orders, 10)
        page_orders = p.get_page(page)
        for item in page_orders:
            customer_realname = Customer.objects.filter(id=item.customer_id).first().realname
            customer_address = Customer.objects.filter(id=item.customer_id).first().address
            result_data.append(
                {
                    "id":item.id,
                    "customer_realname":customer_realname,
                    "customer_address":customer_address,
                    "total":round(item.total, 1),
                    "updatetime":timezone.localtime(item.update_time).strftime("%Y-%m-%d %H:%M:%S"),
                    "status":item.status
                }
            )
    except Exception as err:
        result = False
        message = str(err)
        print(err)
    else:
        result = True
        message = "success!"
    return JsonResponse({"result": result, "message": message, "result_data":result_data, "pagenum":num})


def getallorders_merchant(request):
    """
    商家查询所有订单
    """
    try:
        result_data = []
        status = "订单完成"
        merchant_name = request.POST.get("username")
        page = request.POST.get("page")
        orders = Order.objects.filter(status=status, merchant__user__username=merchant_name)
        num = len(orders)
        p = Paginator(orders, 10)
        page_orders = p.get_page(page)
        for item in page_orders:
            customer_address = Customer.objects.filter(id=item.customer_id).first().address
            customer_realname = Customer.objects.filter(id=item.customer_id).first().realname
            result_data.append(
                {
                    "id":item.id,
                    "customeraddress":customer_address,
                    "customerrealname":customer_realname,
                    "updatetime":timezone.localtime(item.update_time).strftime("%Y-%m-%d %H:%M:%S"),
                    "total":round(item.total, 1),
                    "status":item.status
                }
            )
    except Exception as err:
        result = False
        message = str(err)
    else:
        result = True
        message = "success!"
    return JsonResponse({"result": result, "message": message, "result_data":result_data,"num":num})


def updateorder(request):
    """
    更新订单
    """
    try:
        order_id=request.POST.get("orderid")
        statusprocess = [
            "下单成功",
            "等待商家上门取衣",
            "等待洗衣",
            "洗衣完成",
            "商家送衣",
            "订单完成"
        ]
        now = datetime.datetime.now()
        order = Order.objects.filter(id=order_id).first()
        i = -1
        for index in range(len(statusprocess)):
            if statusprocess[index] == order.status:
                i = index
        if i != 6:
            Order.objects.filter(id=order_id).update(status=statusprocess[i+1], update_time=now)
    except Exception as err:
        result = False
        message = str(err)
        print(err)
    else:
        result = True
        message = "success!"
    return JsonResponse({"result": result, "message": message})


def searchorder(request):
    """
    通过复杂条件搜索订单
    """
    try:
        result_data = []
        start_time = ""
        end_time = ""
        num = 0
        merchant_username = request.POST.get("username")
        page = request.POST.get("page")
        order_id = request.POST.get("orderid")
        customer_realname = request.POST.get("customer")
        time_str = request.POST.get("time")
        status = "订单完成" 
        if len(time_str) > 15:
            start_time = time_str.split(',')[0][2:-1]
            end_time = time_str.split(',')[1][1:-2]
        if  order_id:
            orders = Order.objects.filter(id=order_id, status=status,merchant__user__username=merchant_username) # id是主码
        else:
            if  customer_realname and  len(time_str) > 15: # 时间范围和用户真名
                customer_id = Customer.objects.filter(realname=customer_realname).first().id
                orders = Order.objects.filter(customer_id=customer_id, merchant__user__username=merchant_username, update_time__range=(start_time, end_time), status=status)
            if not customer_realname and len(time_str) > 15: # 时间范围
                orders = Order.objects.filter(merchant__user__username=merchant_username, update_time__range=(start_time, end_time), status=status)
            if  customer_realname and len(time_str) < 15: # 用户真名
                customer_id = Customer.objects.filter(realname=customer_realname).first().id
                orders = Order.objects.filter(merchant__user__username=merchant_username, customer_id=customer_id, status=status)
        num = len(orders)
        p = Paginator(orders, 10)
        page_orders = p.get_page(page)
        for item in page_orders:
            customer_realname = Customer.objects.filter(id=item.customer_id).first().realname
            customer_address = Customer.objects.filter(id=item.customer_id).first().address
            result_data.append(
                {
                    "id":item.id,
                    "customerrealname":customer_realname,
                    "customeraddress":customer_address,
                    "total":round(item.total, 1),
                    "updatetime":timezone.localtime(item.update_time).strftime("%Y-%m-%d %H:%M:%S"),
                    "status":item.status
                }
            )
    except Exception as err:
        result = False
        message = str(err)
        print(err)
    else:
        result = True
        message = "success!"
    return JsonResponse({"result": result, "message": message,"result_data":result_data, "num":num})


def searchorder_customer(request):
    """
    客户通过复杂条件搜索订单
    """
    try:
        result_data = []
        start_time = ""
        end_time = ""
        num = 0
        # orders = []
        customer_username = request.POST.get("username")
        page = request.POST.get("page")
        order_id = request.POST.get("orderid")
        merchant_realname = request.POST.get("merchant")
        time_str = request.POST.get("time")
        status = "订单完成" 
        if len(time_str) > 15:
            start_time = time_str.split(',')[0][2:-1]
            end_time = time_str.split(',')[1][1:-2]
        if  order_id:
            orders = Order.objects.filter(id=order_id, status=status,customer__user__username=customer_username) # id是主码
        else:
            if  merchant_realname and  len(time_str) > 15: # 时间范围和用户真名
                merchant_id = Merchant.objects.filter(realname=merchant_realname).first().id
                orders = Order.objects.filter(merchant_id=merchant_id, customer__user__username=customer_username, update_time__range=(start_time, end_time), status=status)
            if not merchant_realname and len(time_str) > 15: # 时间范围
                orders = Order.objects.filter(customer__user__username=customer_username, update_time__range=(start_time, end_time), status=status)
            if  merchant_realname and len(time_str) < 15: # 商户真名
                merchant_id = Merchant.objects.filter(realname=merchant_realname).first().id
                orders = Order.objects.filter(customer__user__username=customer_username, merchant_id=merchant_id, status=status)
        num = len(orders)
        p = Paginator(orders, 10)
        page_orders = p.get_page(page)
        for item in page_orders:
            merchant_username = Merchant.objects.filter(id=item.merchant_id).first().user.username
            merchant_realname = Merchant.objects.filter(id=item.merchant_id).first().realname
            result_data.append(
                {
                    "id":str(item.id),
                    "merchantusername":merchant_username,
                    "merchantrealname":merchant_realname,
                    "updatetime":timezone.localtime(item.update_time).strftime("%Y-%m-%d %H:%M:%S"),
                    "total":round(item.total, 1),
                    "status":item.status,
                    "isRated":str(item.is_Rated)
                }
            )
    except Exception as err:
        result = False
        message = str(err)
        print(err)
    else:
        result = True
        message = "success!"
    return JsonResponse({"result": result, "message": message,"result_data":result_data, "num":num})


def getincome(request):
    """
    统计收入
    """
    try:
        result_data = []
        cloth_type = []
        cloth_result = {}
        merchant_name = request.POST.get("username")
        status = "订单完成" 
        now = datetime.datetime.utcnow()
        orders = Order.objects.filter()
        for i in range(15):
            past = now + datetime.timedelta(days=-15+i)
            start_time = datetime.datetime(past.year, past.month, past.day, 0, 0)
            end_time = datetime.datetime(past.year, past.month, past.day, 23, 59)
            #orders = Order.objects.filter(merchant__user__username=merchant_name, update_time__month=past.month, update_time__day=past.day, status=status)
            orders = Order.objects.filter(merchant__user__username=merchant_name, status=status, update_time__range=(start_time, end_time))
            income_total = 0
            order_num = len(orders)
            for item in orders:
                cloths = Cloth.objects.filter(order_id=item.id)
                for cloth in cloths:
                    if cloth.type not in cloth_type: # 衣服种类不在数组中，添加入数组中，并记录
                        cloth_type.append(cloth.type)
                        cloth_result.update({
                            cloth.type: cloth.num,
                        })
                    else: # 衣服种类不在数组中，添加入数组中，更新衣服数量
                        cloth_result[cloth.type] += cloth.num
                income_total += item.total
            result_data.append(
                {
                    "income_total":round(income_total, 1),
                    "endtime":past.strftime("%Y-%m-%d"),
                    "order_num":order_num
                }
            )
        cloth_result = sorted(cloth_result.items(),key=lambda x:x[1],reverse=True)
    except Exception as err:
        result = False
        message = str(err)
        print(err)
    else:
        result = True
        message = "success!"
    return JsonResponse({"result": result, "message": message,"result_data":result_data,"cloth_result":cloth_result})


def user_info(argw):
    return JsonResponse({"code": 0, "data": {"id": 1, "username": "3190921049X", "timestamp": 1641291308.4811597}, "message": "ok"})


def rateorder(request):
    """
    评分订单
    """
    try:
        result_data = []
        rated_num = 0
        rates_total = 0
        ratep_total = 0
        rateq_total = 0
        orderid = request.POST.get("orderid")
        rate_speed = request.POST.get("rate_speed")
        rate_price = request.POST.get("rate_price")
        rate_quality = request.POST.get("rate_quality")
        Order.objects.filter(id=orderid).update(rate_speed=rate_speed, rate_price=rate_price, rate_quality=rate_quality,is_Rated=1)
        # 更新商户评分
        merchant_id = Order.objects.filter(id=orderid).first().merchant_id
        orders = Order.objects.filter(merchant=merchant_id, is_Rated=1)
        for order in orders:
            rated_num += 1
            rates_total += order.rate_speed
            ratep_total += order.rate_price
            rateq_total += order.rate_quality
        if orders:
            Merchant.objects.filter(id=merchant_id).update(rate_speed=rates_total/rated_num, rate_price=ratep_total/rated_num, rate_quality=rateq_total/rated_num)
    except Exception as err:
        result = False
        message = str(err)
        print(err)
    else:
        result = True
        message = "success!"
    return JsonResponse({"result": result, "message": message,"result_data":result_data})


def getgoods(request):
    """
    获得全部价格
    """
    try:
        result_data = []
        # sales_dict = {}
        now = datetime.datetime.utcnow()
        past = now + datetime.timedelta(days=-15)
        clothprice = MCloth.objects.all()
        for item in clothprice:
            merchant = Merchant.objects.filter(id=item.merchant_id).first()
            orders = Order.objects.filter(merchant=merchant, update_time__range=(past, now))
            sales = 0
            resent_order_id = []
            for order in orders: # 该商户近15日的订单号
                resent_order_id.append(order.id)
            cloths = Cloth.objects.filter(ClothPrice=item.id)
            if cloths :
                for cloth in cloths:
                    if cloth.order_id in resent_order_id:
                        sales += cloth.num
            else:
                sales = 0
            result_data.append(
                {
                    "sales": sales,
                    "merchant":merchant.user.username,
                    "id":item.id,
                    "type": item.type,
                    "Washmethod": item.Washmethod,
                    "price": item.price
                }
            )
        result_data.sort(key=lambda x:x['sales'],reverse=True)
    except Exception as err:
        result = False
        message = str(err)
    else:
        result = True
        message = "success!"
    return JsonResponse({"result": result, "message": message, "result_data":result_data })


def newplaceorder(request):
    """
    下单函数
    """
    try:
        merchant_list = []
        order_data = json.loads(request.POST.get("data"))
        cusname = request.POST.get("username")
        total = request.POST.get("total")
        Customer_user = Role.objects.filter(username=cusname).first()
        customer = Customer.objects.filter(user=Customer_user).first()
        now = datetime.datetime.now()
        order_dict = {}
        for item in order_data:
            merchant = item['merchant']
            type = item['type']
            Washmethod = item['Washmethod']
            price = item['price']
            num = item['num']
            priceid = item['priceid']
            if Washmethod == '普通洗':
                i = 0
            if Washmethod == '超强洗':
                i = 1
            if num != 0:
                if merchant not in merchant_list:
                    merchant_list.append(merchant)
                    Merchant_user = Role.objects.filter(username=merchant).first()
                    merchant1 = Merchant.objects.filter(user=Merchant_user).first()
                    order = Order.objects.create(merchant_id=merchant1.id, customer_id=customer.id, status = "下单成功", total=0, is_Rated=0, create_time=now, update_time=now)
                    order_dict[merchant] = order
                total = Order.objects.filter(id=order_dict[merchant].id).first().total  + num*price
                Order.objects.filter(id=order_dict[merchant].id).update(total=total)
                Cloth.objects.create(type=type, Washmethod=i, num=num, price=price, order_id=order_dict[merchant].id, ClothPrice=priceid)# 订单中衣服中的某类衣服及其数量

    except Exception as err:
        result = False
        message = str(err)
        print(err)
    else:
        result = True
        message = "success!"
    return JsonResponse({"result": result, "message": message,"result_data":order_data})


def searchgoods(request):
    """
    搜索获得价格
    """
    try:
        keyword = request.POST.get("keyword")
        result_data = []
        clothprice = MCloth.objects.filter(Q(type__contains=keyword))
        if clothprice:
            for item in clothprice:
                merchant = Merchant.objects.filter(id=item.merchant_id).first()
                result_data.append(
                    {
                        "merchant":merchant.user.username,
                        "id":item.id,
                        "type": item.type,
                        "Washmethod": item.Washmethod,
                        "price": item.price
                    }
                )
    except Exception as err:
        result = False
        message = str(err)
    else:
        result = True
        message = "success!"
    return JsonResponse({"result": result, "message": message, "result_data":result_data })